package com.itheima.filter;

import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

//@WebFilter("/*")
@Slf4j
public class LoginCheckFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //0.强转对象
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        //1.获取请求url
        // StringBuffer requestURL = req.getRequestURL();获取全部路径包含协议和端口和资源
        String requestURI = req.getRequestURI();//只获取资源路径
        //2.判断url是否包含login(登录路径)，如果包含则放行
        if (requestURI.contains("login")) {
            chain.doFilter(request, response);
            //注意：一定要结束当前请求，不应该继续执行代码逻辑
            return;
        }
        //3.获取请求头中的令牌（token）
        String token = req.getHeader("token");
        //4.判断令牌是否存在
        if (token == null) {
            res.setStatus(401);
            return;
        }
        //5.解析token，如果解析失败则响应401
        try {
            Claims claims = JwtUtils.parseJWT(token);
        } catch (Exception e) {
            res.setStatus(401);
            return;
        }
        //6.放行
        chain.doFilter(request, response);


    }
}
